import { NodeStatus } from "../../../common/Enum";
import BTComposite from "../../Base/BTComposite";

/** 并行节点，可同时运行多个节点，所有子节点返回ture就返回true，一个false返回false，否则返回running */
export default class CompositeParallel extends BTComposite {

    executionStatus: NodeStatus[] = []

    get status() {
        let childrenComplete = true
        for (let i = 0; i < this.executionStatus.length; i++) {
            if (this.executionStatus[i] === NodeStatus.Running) {
                childrenComplete = false
            } else if (this.executionStatus[i] === NodeStatus.Failure) {
                return NodeStatus.Failure
            }
        }
        return childrenComplete ? NodeStatus.Success : NodeStatus.Running
    }

    set status(newStatus) {
    }

    onStart(): void {
        super.onStart()
        this.index = 0
        this.executionStatus = new Array(this.children.length)
        for (let i = 0; i < this.executionStatus.length; i++) {
            this.executionStatus[i] = NodeStatus.Inactive
        }
    }

    canExecute(): boolean {
        return this.index < this.children.length
    }

    onChildExecuted(status: NodeStatus, index: number): void {
        this.executionStatus[index] = status
    }


    onConditionalAbort(index: number) {
        this.index = 0
        this.executionStatus = new Array(this.children.length)
        for (let i = 0; i < this.executionStatus.length; i++) {
            this.executionStatus[i] = NodeStatus.Inactive
        }
    }

    canRunParallelChildren() {
        return true
    }

    onChildStarted() {
        this.executionStatus[this.index] = NodeStatus.Running
        this.index++
    }
}